package cn.itcast.eduservice.service.impl;

import cn.itcast.eduservice.entity.EduChapter;
import cn.itcast.eduservice.entity.EduVideo;
import cn.itcast.eduservice.entity.chapter.ChapterVo;
import cn.itcast.eduservice.entity.chapter.VideoVo;
import cn.itcast.eduservice.mapper.EduChapterMapper;
import cn.itcast.eduservice.service.EduChapterService;
import cn.itcast.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Duanzihuang
 * @since 2020-05-19
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    EduVideoService eduVideoService;

    @Override
    public List<ChapterVo> getChapterVideoById(String courseId) {
        // 根据课程id获取chapter列表
        QueryWrapper<EduChapter> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id",courseId);
        List<EduChapter> chapterList = baseMapper.selectList(chapterWrapper);

        // 根据课程id获取video列表
        QueryWrapper<EduVideo> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id",courseId);
        List<EduVideo> videoList = eduVideoService.list(videoWrapper);

        // 对上面的数据进行整合
        List<ChapterVo> finalChapterList = new ArrayList<>();

        for (int i = 0; i <chapterList.size() ; i++) {
            EduChapter eduChapter = chapterList.get(i);
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);

            finalChapterList.add(chapterVo);


            List<VideoVo> tempVideoList = new ArrayList<>();
            for (int m = 0; m <videoList.size() ; m++) {
                EduVideo eduVideo = videoList.get(m);

                if (eduChapter.getId().equals(eduVideo.getChapterId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(eduVideo,videoVo);

                    tempVideoList.add(videoVo);
                }
            }

            chapterVo.setChildren(tempVideoList);
        }

        return finalChapterList;
    }

    @Override
    public void removeChapterByCourseId(String courseId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("course_id",courseId);

        baseMapper.delete(wrapper);
    }
}
